<?php

namespace app\model\game;

use app\base\BaseModel;
use app\model\user\UserBeanLogModel;
use app\model\user\UserBeanPredictModel;
use app\model\user\UserModel;
use app\model\user\UserSettlementModel;

/**
 * 模型-GameUserModel
 * Class GameUser
 * @package app\model
 */
class GameProcessModel extends BaseModel
{
    protected $name = 'game_process';

    /**
     * 获取分页列表
     * @param $user_id
     * @param $current_page
     * @param $list_rows
     * @param string $field
     * @return array
     */
    public function getPageData($user_id, $current_page, $list_rows, $field = '*')
    {
        $dataList = $this
            ->UserId($user_id)
            ->field($field)
            ->order('add_time', 'desc')
            ->paginate(['page' => $current_page, 'list_rows' => $list_rows], false);
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        return ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $dataList->items()];
    }

    /**
     * 盲盒游戏记录获取
     * @param string $user_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getGameRecord($user_id = '')
    {
        $bean = UserModel::getBean($user_id);
        $bean_earnings = UserModel::getBeanEarnings($user_id);
        $bean = floatval($bean) + floatval($bean_earnings);
        $card = GameUserModel::getCardClassNum($user_id, 1);
        $box = GameUserModel::getCardClassNum($user_id, 2);
        $game_list = self::where('user_id', $user_id)->order('id DESC')->limit(15)->select();
        $game_arr = [];
        foreach ($game_list as $value) {
            $win_str = "(" . $value['number'] . ")次 未抽中";
            if ($value['open_time'] > time()) {
                $win_str = "待开奖";
            }
            $open_time = date("m-d H:i", $value['open_time']);
            if (intval($value['win']) == 2) {
                $win_str = "(" . $value['number'] . ")次 抽中了";
                if ($value['open_time'] > time()) {
                    $win_str = "待开奖 ";
                    $win_str = "(" . $value['number'] . ")次 待开奖";
                }
                switch ($value['type']) {
                    case 1:
                        $win_str .= "铜卡";
                        break;
                    case 2:
                        $win_str .= "银卡";
                        break;
                    case 3:
                        $win_str .= "金卡";
                        break;
                    case 4:
                        $win_str .= "钻卡";
                        break;
                }
            }
            $game_arr[] = [
                'tag' => $win_str,
                'time' => $open_time
            ];
        }
        $map = [
            'user_id' => $user_id,
            'open' => 1
        ];
        $game = self::where($map)->field('open_time')->find();
        if (!empty($game)) {
            $count = $game['open_time'] - time();
            $game['count'] = $count;
        }
        $map = [
            'user_id' => $user_id,
            'day' => date("Y-m-d")
        ];
        $pay = self::where($map)->sum('number');
        $rem = 15 - $pay;
        $map['win'] = 2;
        $win_temp = self::where($map)->find();
        if (empty($win_temp)) {
            $win = 0;
        } else {
            $win = 1;
        }
        return ['bean' => $bean,
            'card' => $card,
            'box' => $box,
            'pay' => $pay,
            'rem' => $rem,
            'win' => $win,
            'game_list' => $game_arr,
            'now_game' => $game
        ];
    }

    /**
     * 盲盒游戏返佣结算
     * @param $start_time
     * @param $end_time
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getSettleSale($start_time, $end_time)
    {
        $map1 = [
            'settlement' => 0,
            'open' => 2,
            'win' => 2
        ];
        $list_bean = self::whereBetween('add_time', $start_time . "," . $end_time)->where($map1)->field('user_id,type')->select();
        $add_card_ids = [];
        $add_card = [];
        foreach ($list_bean as $value) {
            $add_card_ids[] = $value['user_id'];
            $add_card[intval($value['user_id'])] = $value['type'];
        }
        $map1 = [
            'settlement' => 0,
            'open' => 2,
        ];
        $list_bean = self::whereBetween('add_time', $start_time . "," . $end_time)->where($map1)->field('id,user_id,SUM(bean) as bean_all,SUM(return_capital) as return_capital_all,SUM(return_earnings) as return_earnings_all,SUM(return_bean) as return_bean_all')->group('user_id')->select();
        foreach ($list_bean as $value) {
            UserBeanLogModel::changeEarningsBean($value['user_id'], $value['return_capital_all'] + $value['return_earnings_all'], "return", "未中奖退还本金");
//            UserBeanLogModel::changeEarnings($value['user_id'], $value['return_earnings_all'], "add", "未中奖退还利润", 1);
            UserBeanLogModel::changeEarnings($value['user_id'], $value['return_bean_all'], "add", "未中奖补贴", 3);
            $day = date("Y-m-d", $end_time);
            UserSettlementModel::addSettlementBean($value['user_id'], $value['bean_all'], $day, $value['return_bean_all']);
            $up_data = [
                'settlement' => 1,//更新结算
            ];
            $ret = self::where('user_id', $value['user_id'])->update($up_data);
            if ($ret !== false && in_array($value['user_id'], $add_card_ids)) {
                GameUserModel::addCard($value['user_id'], $add_card[intval($value['user_id'])]);
            }
        }
        $day = date("Y-m-d", $end_time);
        UserBeanPredictModel::clearEarnings($day);
        return $list_bean;
    }

    /**
     * 参与游戏
     * @param int $user_id
     * @param int $type
     * @param int $number 产生次数
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function addGameProcess($user_id = 0, $type = 1, $number = 1)
    {
        $out_data = [
            'code' => 0,
            'msg' => '参与失败'
        ];
        if ($type > 4 || $type < 1) {
            return $out_data;
        }
        $h = intval(date("H"));
        if ($h >= 9 && $h <= 22) {
            $map = [
                'user_id' => $user_id,
                'day' => date("Y-m-d")
            ];
            //取消中奖后的限制
//            $temp_game = self::where($map)->where('win', 2)->find();
//            if (!empty($temp_game)) {
//                $out_data = [
//                    'code' => 11,
//                    'msg' => "今日已抽中,明天再来参与吧"
//                ];
//                return $out_data;
//            }
            $user_model = new UserModel();
            $user_data = $user_model->where('id', $user_id)->field('member_level')->find();
            if (intval($user_data['member_level']) < 2) {
                $map1 = [
                    'user_id' => $user_id,
                ];
                $count_temp = self::where($map1)->sum('number');
                if ($count_temp >= 15) {
                    UserModel::setVipLevel($user_id, "V");
                }
            }
            $count = self::where($map)->sum('number');
            if (($count + $number) > 15) {
                $out_data = [
                    'code' => 10,
                    'msg' => "一天最多只能参与15次,还剩余" . (15 - $count) . "次"
                ];
                return $out_data;
            }

            $type_arr = GameTypeModel::getTypeList();
            $deduct = $type_arr[intval($type)]['deduct'];
            $bean = $type_arr[intval($type)]['deduct'] * $number;
            $name = "";
            $return_capital = $deduct * $number;
            $return_bean = $return_capital * 0.02;
            $user_bean = UserModel::getBean($user_id);
            $user_bean_earnings = UserModel::getBeanEarnings($user_id);
            $sub_bean = 0;
            if (($user_bean + $user_bean_earnings) < $bean) {
                return [
                    'code' => 0,
                    'msg' => '趣豆数量不足'
                ];
            }
            if ($user_bean > $bean) {
                //扣除对应盲盒的趣豆数量
                $out_data = UserBeanLogModel::changeEarningsBean($user_id, $bean, "sub", "参与盲盒活动");
                if (empty($out_data['code'])) {
                    return $out_data;
                }
            } else {
                //扣除对应盲盒的趣豆数量(本金)
                if (intval($user_bean) > 0) {
                    $out_data = UserBeanLogModel::changeEarningsBean($user_id, $user_bean, "sub", "参与盲盒活动");
                    if (empty($out_data['code'])) {
                        return $out_data;
                    }
                }
                $sub_bean = floatval($bean) - floatval($user_bean);
                if ($sub_bean > 0) {
                    //扣除对应盲盒的趣豆数量(收益)
                    $out_data = UserBeanLogModel::changeEarnings($user_id, $sub_bean, "sub", "参与盲盒活动");
                    if (empty($out_data['code'])) {
                        UserBeanLogModel::changeEarningsBean($user_id, $user_bean, "return", "参与失败退还");
                        return $out_data;
                    }
                }
            }
            switch ($type) {
                case 1:
                    $name = "盲盒抽铜卡";
                    break;
                case 2:
                    $name = "盲盒抽银卡";
                    break;
                case 3:
                    $name = "盲盒抽金卡";
                    break;
                case 4:
                    $name = "盲盒抽钻卡";
                    break;
            }
            $win_num = rand(1, 20);
            $win = 1;
            $map = [
                'user_id' => $user_id,
                'win' => 2
            ];
            $win_data = self::where($map)->order('id DESC')->find();
            if (!empty($win_data)) {
                $map = [
                    'user_id' => $user_id,
                    'win' => 1
                ];
                $count = self::where($map)->where('id', '>', $win_data['id'])->sum('number');
            } else {
                $map = [
                    'user_id' => $user_id,
                    'win' => 1
                ];
                $count = self::where($map)->sum('number');
            }
            //收益部分
            $return_earnings = $sub_bean;
            $return_capital = $bean - $return_earnings;
            $card_num = GameUserModel::getCardNum($user_id, $type);
            if ($card_num == 4) {
                //如果当前卡已经有4张了 最后一张卡中奖必须大于31次不中
                if (intval($count + $number) >= 31) {
                    $win = 2;
                    $return_capital = $deduct * ($number - 1);
                    $return_bean = $return_capital * 0.02;
                    //如果返回趣豆本金大于收益金额
                    if ($return_capital > $sub_bean) {
                        $return_earnings = $sub_bean;
                        $return_capital = $return_capital - $sub_bean;
                    } else {
                        $return_earnings = $return_capital;
                        $return_capital = 0;
                    }
                }
            } else {
                if (intval($count + $number) >= 15) {
                    //15次连抽必中一次
                    $win = 2;
                    $return_capital = $deduct * ($number - 1);
                    $return_bean = $return_capital * 0.02;
                    //如果返回趣豆本金大于收益金额
                    if ($return_capital > $sub_bean) {
                        $return_earnings = $sub_bean;
                        $return_capital = $return_capital - $sub_bean;
                    } else {
                        $return_earnings = $return_capital;
                        $return_capital = 0;
                    }
                } else {
                    if (intval($win_num) == 15) {
                        //正常概率 10次中一次
                        $win = 2;
                        $return_capital = $deduct * ($number - 1);
                        $return_bean = $return_capital * 0.02;
                        //如果返回趣豆本金大于收益金额
                        if ($return_capital > $sub_bean) {
                            $return_earnings = $sub_bean;
                            $return_capital = $return_capital - $sub_bean;
                        } else {
                            $return_earnings = $return_capital;
                            $return_capital = 0;
                        }
                    }
                }
            }
            $in_data = [
                'user_id' => $user_id,
                'name' => $name,
                'type' => $type,
                'detail' => "抽取卡片 有5%的中奖概率",
                'bean' => $bean,
                'number' => $number,
                'return_bean' => $return_bean,
                'return_capital' => $return_capital,
                'return_earnings' => $return_earnings,
                'win' => $win,
                'day' => date("Y-m-d"),
                'add_time' => time(),
                'open_time' => time()
            ];
            //及时开奖
            $ret = self::insert($in_data);
            if ($ret == false) {
                $out_data = [
                    'code' => 0,
                    'msg' => '参与失败'
                ];
                return $out_data;
            }
            $game_id = self::getLastInsID();
            //预结算
            $day = date("Y-m-d");
            UserModel::upGameNow($user_id, $return_bean, $day, $game_id);
            $out_data = [
                'code' => 1,
                'msg' => '参与成功'
            ];
            return $out_data;
        } else {
            $out_data = [
                'code' => 0,
                'msg' => '活动只在09:00-22:00间开启'
            ];
            return $out_data;
        }
    }

    /**
     * 开奖完成
     * @param int $user_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function upGameProcess($user_id = 0)
    {
        if (empty($user_id)) {
            $map = [
                'open' => 1
            ];
        } else {
            $map = [
                'user_id' => $user_id,
                'open' => 1
            ];
        }
        $list = self::where($map)->where('open_time', '<=', time())->select();
        $type_arr = [];
        foreach ($list as $value) {
            if (intval($value['win']) == 2) {
                //中奖。获取指定卡
//                GameUserModel::addCard($user_id, $value['type']);
                $type_arr[] = $value['type'];
            } else {
                // 未中奖 退还 趣豆
//                UserBeanLogModel::changeEarnings($user_id, $value['bean'], "add", "参与盲盒活动未中奖");
            }
        }
        $up_data = [
            'open' => 2
        ];
        $ret = self::where($map)->where('open_time', '<=', time())->update($up_data);
        if ($ret == false) {
            return [
                'code' => 0,
                'msg' => '开奖失败'
            ];
        }
        return [
            'code' => 1,
            'data' => $type_arr,
            'msg' => '开奖成功'
        ];
    }

    /**
     * 获取用户趣豆玩法情况
     * @param array $user_ids
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getUserListPopSum($user_ids = [])
    {
        $time_start = strtotime("2022-10-09");
        $time_end = time();
        $order_list = self::whereIn('user_id', $user_ids)
            ->where('add_time', '>=', $time_start)
            ->where('add_time', '<=', $time_end)
            ->field('id,SUM(return_capital) as all_return_capital,SUM(return_earnings) as all_return_earnings,user_id')
            ->group('user_id')
            ->select();
        $user_data = [];
        foreach ($order_list as $value) {
            if (!isset($user_data[intval($value['user_id'])])) {
                $user_data[intval($value['user_id'])]['total'] = 0;
                $user_data[intval($value['user_id'])]['order_ids'] = [];
                $user_data[intval($value['user_id'])]['total'] += ($value['all_return_capital'] + $value['all_return_earnings']);
                $user_data[intval($value['user_id'])]['order_ids'][] = $value['id'];
            } else {
                $user_data[intval($value['user_id'])]['total'] += ($value['all_return_capital'] + $value['all_return_earnings']);
                $user_data[intval($value['user_id'])]['order_ids'][] = $value['id'];
            }
        }
        foreach ($user_ids as $value) {
            if (!isset($user_data[intval($value)]['total'])) {
                $user_data[intval($value)]['total'] = 0;
                $user_data[intval($value)]['order_ids'] = [];
            }
        }
        return $user_data;
    }

    /**
     * 获取用户趣豆玩法情况
     * @param array $user_ids
     * @param $time_start
     * @param $time_end
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getUserListPop($user_ids = [], $time_start, $time_end)
    {
        $order_list = self::whereIn('user_id', $user_ids)
            ->where('add_time', '>=', $time_start)
            ->where('add_time', '<=', $time_end)
            ->field('id,return_capital,return_earnings,user_id')
            ->select();
        $user_data = [];
        foreach ($order_list as $value) {
            if (!isset($user_data[intval($value['user_id'])])) {
                $user_data[intval($value['user_id'])]['total'] = 0;
                $user_data[intval($value['user_id'])]['order_ids'] = [];
                $user_data[intval($value['user_id'])]['total'] += ($value['return_capital'] + $value['return_earnings']);
                $user_data[intval($value['user_id'])]['order_ids'][] = $value['id'];
            } else {
                $user_data[intval($value['user_id'])]['total'] += ($value['return_capital'] + $value['return_earnings']);
                $user_data[intval($value['user_id'])]['order_ids'][] = $value['id'];
            }
        }
        foreach ($user_ids as $value) {
            if (!isset($user_data[intval($value)]['total'])) {
                $user_data[intval($value)]['total'] = 0;
                $user_data[intval($value)]['order_ids'] = [];
            }
        }
        return $user_data;
    }

    /**
     * 获取用户趣豆玩法情况
     * @param array $user_ids
     * @param $time_start
     * @param $time_end
     * @return float|int
     */
    public static function getUserListCons($user_ids = [], $time_start, $time_end)
    {
        $bean_count = self::whereIn('user_id', $user_ids)
            ->where('add_time', '>=', $time_start)
            ->where('add_time', '<=', $time_end)
            ->sum('return_capital');

        $earnings_count = self::whereIn('user_id', $user_ids)
            ->where('add_time', '>=', $time_start)
            ->where('add_time', '<=', $time_end)
            ->sum('return_earnings');
        $bean_count = $bean_count + $earnings_count;
        if (empty($bean_count)) {
            return 0;
        }
        return $bean_count;
    }

    /**
     * 上一周盲盒参与次数是否瞒住条件
     * @param string $user_id
     * @param int $number
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function isLastWeek($user_id = '', $number = 20)
    {
        $map = [
            'user_id' => $user_id
        ];
        $game = self::where($map)->order('id ASC')->field('add_time')->find();
        if (empty($game)) {
            //没有参与过
            return true;
        }
        $add_time = $game['add_time'];
        //上周一的 00:00
        $last_m = strtotime(date("Ymd", strtotime("-1 week Sunday") - (3600 * 24 * 6)));
        if ($add_time > $last_m) {
            //如果玩的时间还没到一周
            return true;
        }
        $last_e = strtotime(date("Ymd", strtotime("-1 week Sunday") + (3600 * 24)));
        $number_w = self::where($map)->whereBetween('add_time', $last_m . "," . $last_e)->sum('number');
        if ($number_w > $number) {
            //瞒住结算条件
            return true;
        }
        return false;
    }

    /**
     * 获取今日即将返回的
     * @param string $user_id
     * @return float
     */
    public static function getBeanPredict($user_id = '')
    {
        $map = [
            'user_id' => $user_id,
            'settlement' => 0,
            'day' => date("Y-m-d")
        ];
        $return_bean = self::where($map)->sum('return_bean');
        $return_capital = self::where($map)->sum('return_capital');
        return $return_bean + $return_capital;
    }

    /**
     * 获取今日结算收益
     * @param string $user_id
     * @return float
     */
    public static function getDayBeanEarnings($user_id = '')
    {
        $map = [
            'user_id' => $user_id,
            'earnings' => 2
        ];
        $time_s = time() - (3600 * 24);
        $time_e = time();
        $user_bean_model = new UserBeanLogModel();
        return $user_bean_model->where($map)->whereBetween('add_time', $time_s . "," . $time_e)->whereIn('type', 'add')->sum('bean');
    }
}